"""
绘图样式与中文字体配置，确保跨平台中文显示。
"""
from typing import Dict, Any
import matplotlib
import matplotlib.pyplot as plt
import time
from rich.console import Console
from rich.panel import Panel
from rich.text import Text

_console = Console()


def set_chinese_font(font_family: str = "Heiti TC", quiet: bool = True) -> None:
	"""Set Chinese font for matplotlib plots.

	Args:
		font_family: name of the font family to set. Default: Heiti TC (Mac recommended).
	"""
	try:
		plt.rcParams['font.sans-serif'] = [font_family]
		plt.rcParams['axes.unicode_minus'] = False
		if not quiet:
			_console.log(f"字体配置已加载：{plt.rcParams['font.sans-serif']}")
	except Exception as e:
		if not quiet:
			_console.log(f"设置中文字体时出错：{e}")


def set_plot_style(style_cfg: Dict[str, Any] = None) -> None:
	"""Set matplotlib/seaborn style and Chinese font for Mac/Windows.

	Args:
		style_cfg: dict, e.g. from config.yaml['plot'] containing keys:
			style, dpi, figsize, bbox_inches, font_family
	"""
	if style_cfg is None:
		style_cfg = {
			'style': 'darkgrid',
			'dpi': 300,
			'figsize': [8, 6],
			'bbox_inches': 'tight',
			'font_family': 'Heiti TC'
		}

	# Font
	font_family = style_cfg.get('font_family', 'Heiti TC')
	matplotlib.rcParams['font.sans-serif'] = [font_family]
	matplotlib.rcParams['axes.unicode_minus'] = False

	# Seaborn/matplotlib style
	try:
		import seaborn as sns
		plt_style = style_cfg.get('style', 'darkgrid')
		sns.set_style(plt_style)
	except Exception:
		# seaborn optional; fallback to matplotlib defaults
		plt_style = style_cfg.get('style', 'default')
		matplotlib.style.use(plt_style)

	# Figure defaults
	plt.rcParams['figure.dpi'] = style_cfg.get('dpi', 300)
	plt.rcParams['figure.figsize'] = style_cfg.get('figsize', [8, 6])
	plt.rcParams['savefig.bbox'] = style_cfg.get('bbox_inches', 'tight')


def force_chinese_font(ax, font_family: str = 'Heiti TC'):
	"""Force text elements on an Axes to use the Chinese font family.

	This helps when parts of the figure (like legends) don't pick up rcParams.
	"""
	try:
		for label in ax.get_xticklabels() + ax.get_yticklabels():
			label.set_fontfamily(font_family)
		ax.xaxis.label.set_fontfamily(font_family)
		ax.yaxis.label.set_fontfamily(font_family)
		ax.title.set_fontfamily(font_family)
		legend = ax.get_legend()
		if legend:
			# set title and texts
			try:
				legend.set_title(legend.get_title().get_text(), fontfamily=font_family)
			except Exception:
				pass
			for text in legend.get_texts():
				text.set_fontfamily(font_family)
	except Exception as e:
		_console.log(f"force_chinese_font 出错：{e}")


def print_start(label: str = None) -> float:
	"""Print a standard start banner and return start time.

	Args:
		label: optional label to include in the message (e.g. '程序' or '代码尝试')

	Returns:
		start_time (float, epoch seconds)
	"""
	label = f" {label}" if label else ""
	start_time_str = time.strftime('%Y-%m-%d %H:%M:%S')
	start_time = time.time()
	text = Text(f"⏱{label} 开始 {start_time_str}", style="bold green")
	_console.print(Panel(text, expand=False))
	return start_time


def print_end(start_time: float, label: str = None) -> None:
	"""Print a standard end banner and duration since start_time.

	Args:
		start_time: epoch seconds returned by print_start
		label: optional label to include in the message
	"""
	label = f" {label}" if label else ""
	end_time_str = time.strftime('%Y-%m-%d %H:%M:%S')
	end_time = time.time()
	duration = end_time - start_time
	body = Text()
	body.append(f"⌛️{label} 结束 {end_time_str}\n", style="bold cyan")
	body.append(f"总耗时：{int(duration)} 秒（{duration/60:.2f} 分钟）", style="yellow")
	_console.print(Panel(body, expand=False))
